package com.hrt.datasender.dataschedule;

import java.io.File;
import java.util.Date;

import org.quartz.JobExecutionContext;

import com.btcode.common.MyLog;
import com.btcode.log.ILog;
import com.btcode.schedule.SingleInstanceJob;

public class DeleteLogScheduler extends SingleInstanceJob {

    public static String logBasePath;
    private final int logRetentTime = 1000 * 60 * 60 * 24 * 3;
    private final int zipRetentTime = 1000 * 60 * 60 * 24 * 360;

    private ILog log;

    @Override
    public void initJob(JobExecutionContext arg0) {
        log = MyLog.getInstance().getLogger(getClass());
    }

    @Override
    public void myExecute(JobExecutionContext arg0) {

        File dir = new File(logBasePath);

        if (!dir.exists() || !dir.isDirectory()) {
            log.error(logBasePath + ",不存在或者不是目录");
            return;
        }

        File[] files = dir.listFiles();
        
        if(files != null) {
            for (File file : files) {
                long timeLong = file.lastModified();
                long currentTime = new Date().getTime();
    
                long diff = currentTime - timeLong;

                String fileName = file.getName();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

                switch (suffix){
                    case "log":
                        break;
                    case "zip":
                        deleteFile(diff,zipRetentTime,file);
                        break;
					default:
						deleteFile(diff,logRetentTime,file);
						break;
                }

            }
        }
    }

    private void deleteFile(long diff,int retentTime,File file){
        if (diff > retentTime) {
            boolean result = file.delete();

            if (!result) {
                log.error("删除文件失败：" + file.getPath());
            }
            else {
                log.info("文件删除成功：" + file.getPath());
            }
        }
    }

}
